package com.cm.sys.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.cm.sys.framework.utils.IpAddressUtil;

/****
 * 跨域过滤器
 * 
 * @author yuqiang
 * @date 2019/07/08
 */
@Component
public class CorsFilter implements Filter {
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)res;
        HttpServletRequest request = (HttpServletRequest)req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS,PATCH, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        String ip = IpAddressUtil.getIpAddress(request);
        logger.info("*********************************过滤器被使用**************************");
        logger.info("请求的路径============【{}】===============", request.getServletPath());
        logger.info("获得请求的方式*************【{}】*****************", request.getMethod());
        logger.info("获得请求的路由***【{}】***************", request.getRequestURI());
        logger.info("获得请求的ip***【{}】***************", ip);

        chain.doFilter(req, res);

    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}